package com.artisan.requestbodycache.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 演示控制器：验证 Request Body 可重复读取
 */
@RestController
public class DemoController {
    
    private static final Logger log = LoggerFactory.getLogger(DemoController.class);

    /**
     * 测试接口：读取两次 Body，验证可重复读
     * 
     * 测试命令：
     * curl -X POST http://localhost:8080/demo \
     *      -H "Content-Type: application/json" \
     *      -d '{"name":"kimi","age":18}'
     */
    @PostMapping("/demo")
    public String twice(@RequestBody String body, HttpServletRequest req) throws IOException {
        log.info("=== 1. @RequestBody 注入 ===");
        log.info("Body 内容: {}", body);
        
        log.info("=== 2. 手动再读一次（验证可重复读）===");
        String again = new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        log.info("再次读取: {}", again);
        
        // 验证两次读取内容一致
        boolean isSame = body.equals(again);
        log.info("两次读取是否一致: {}", isSame);
        
        return String.format("{\"success\": true, \"message\": \"Body 可重复读取\", \"consistent\": %s}", isSame);
    }

    /**
     * 测试接口2：模拟多个组件读取 Body
     * 场景：日志切面、参数校验、Controller 都需要读 Body
     */
    @PostMapping("/multi-read")
    public String multiRead(HttpServletRequest req) throws IOException {
        log.info("=== 模拟多次读取场景 ===");
        
        // 第1次读取：模拟日志切面
        String read1 = new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        log.info("日志切面读取: {}", read1);
        
        // 第2次读取：模拟参数校验
        String read2 = new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        log.info("参数校验读取: {}", read2);
        
        // 第3次读取：模拟 Controller 业务逻辑
        String read3 = new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        log.info("业务逻辑读取: {}", read3);
        
        boolean allSame = read1.equals(read2) && read2.equals(read3);
        
        return String.format(
            "{\"success\": true, \"message\": \"三次读取完成\", \"allConsistent\": %s, \"content\": \"%s\"}", 
            allSame, read1.replace("\"", "\\\"")
        );
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public String health() {
        return "{\"status\": \"ok\", \"message\": \"Request Body Cache 服务运行正常\"}";
    }
}

